package mjson

import (
	"errors"
	"strconv"

	jsoniter "github.com/json-iterator/go"

	"gitee.com/git-lz/twelve/common/merrors"
)

var JsonIter = jsoniter.ConfigCompatibleWithStandardLibrary

type MRawMessage jsoniter.RawMessage

func NewMRawMessage() *MRawMessage {
	return &MRawMessage{}
}

func (m *MRawMessage) Convert(out interface{}) error {
	if m == nil {
		return errors.New(merrors.ErrMsgDataIsEmpty)
	}

	tx := m
	return JsonIter.Unmarshal(*tx, &out)
}

func (m *MRawMessage) ConvertInt64() ([]int64, error) {
	if m == nil {
		return nil, errors.New(merrors.ErrMsgDataIsEmpty)
	}

	var strArr []string
	tx := m
	err := JsonIter.Unmarshal(*tx, &strArr)
	if err != nil {
		return nil, err
	}

	intArr := make([]int64, len(strArr))
	for i, str := range strArr {
		intArr[i], err = strconv.ParseInt(str, 10, 64)
		if err != nil {
			return nil, err
		}
	}
	return intArr, nil
}

func GetRawFromInterface(input interface{}) (MRawMessage, error) {
	return JsonIter.Marshal(input)
}

func UnmarshalFromInterface(input, output interface{}) error {
	temp, err := JsonIter.Marshal(input)
	if err != nil {
		return err
	}

	if err := JsonIter.Unmarshal(temp, output); err != nil {
		return err
	}

	return nil
}
